package com.zbw.printlibrary.printSub;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.net.Network;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.zbw.printlibrary.bean.AttributeBean;
import com.zbw.printlibrary.printConnector.IPrintCallBack;
import com.zbw.printlibrary.printConnector.NewPrint;
import com.zbw.printlibrary.printConnector.PrinterControlCommon;
import com.zbw.printlibrary.util.PrintSharedPreferencesUtils;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.BIND_AUTO_CREATE;
import net.posprinter.posprinterface.IMyBinder;
import net.posprinter.posprinterface.ProcessData;
import net.posprinter.posprinterface.TaskCallback;
import net.posprinter.service.PosprinterService;
import net.posprinter.utils.BitmapProcess;
import net.posprinter.utils.BitmapToByteData;
import net.posprinter.utils.DataForSendToPrinterPos58;
import net.posprinter.utils.DataForSendToPrinterPos80;
import net.posprinter.utils.StringUtils;

/**
 * Created by cyj on 2019-07-25.
 * 蓝牙打印
 */

public class PrintBluetooth extends PrinterControlCommon {
    private IMyBinder binder;//IMyBinder接口，所有可供调用的连接和发送数据的方法都封装在这个接口内
    private Context mContext;
    private IPrintCallBack mCallBack;
    public static  boolean isConnect;
//    public static  boolean isCT;
    public PrintBluetooth(@NonNull Context context, IPrintCallBack callback) {
        Log.i("PrintBluetooth", "初始化" );
        mContext = context;
        this.mCallBack = callback;

    }

    @Override
    public void connectPrinter() {
        Intent intent = new Intent(mContext, PosprinterService.class);
        mContext.bindService(intent, conn, BIND_AUTO_CREATE);
    }

    @Override
    public void disConnectPrinter() {
        Intent intent=new Intent(mContext,PosprinterService.class);
        mContext.stopService(intent);
        mContext.unbindService(conn);
        // isConnect=false;
        myDisBlueConnect();
    }


    @Override
    public void printTest(final List<String> lists) {

        binder.WriteSendData(new TaskCallback() {
            @Override
            public void OnSucceed() {
                // TODO Auto-generated method stub
                // Toast.makeText(mContext, "打印成功", Toast.LENGTH_SHORT).show();
                mCallBack.onPrintResult(true);
            }
            @Override
            public void OnFailed() {
                // TODO Auto-generated method stub
                mCallBack.onPrintResult(false);
                //  Toast.makeText(mContext, "打印失败", Toast.LENGTH_SHORT).show();
            }
        }, new ProcessData() {//第二个参数是ProcessData接口的实现
            //这个接口的重写processDataBeforeSend这个处理你要发送的指令
            @Override
            public List<byte[]> processDataBeforeSend() {
                //通过工具类得到一个指令的byte[]数据,以文本为例
                List<byte[]> list = new ArrayList<>();
                for (int i = 0; i < lists.size(); i++) {
                    list.add(DataForSendToPrinterPos58.initializePrinter());
                    if(i == 0 || i == 1 ){
                        list.add(DataForSendToPrinterPos58.selectCharacterSize(17));//字体放大一倍
                        list.add(DataForSendToPrinterPos58.selectAlignment(1));//居中
                        list.add(StringUtils.strTobytes(lists.get(i)));
                        list.add(DataForSendToPrinterPos58.printAndFeedLine());
                    }else {
                        list.add(StringUtils.strTobytes(lists.get(i)));
                        list.add(DataForSendToPrinterPos58.printAndFeedLine());
                    }
                }
                byte[] cut = {0x1D, 0x56, 0x00};
                list.add(cut);
                return list;
            }
        });
    }

    @Override
    public void printString(final List<AttributeBean> lists) {
        binder.WriteSendData(new TaskCallback() {
            @Override
            public void OnSucceed() {
                // TODO Auto-generated method stub
                // Toast.makeText(mContext, "打印成功", Toast.LENGTH_SHORT).show();
                mCallBack.onPrintResult(true);
            }
            @Override
            public void OnFailed() {
                // TODO Auto-generated method stub
                mCallBack.onPrintResult(false);
                //  Toast.makeText(mContext, "打印失败", Toast.LENGTH_SHORT).show();
            }
        }, new ProcessData() {//第二个参数是ProcessData接口的实现
            //这个接口的重写processDataBeforeSend这个处理你要发送的指令
            @Override
            public List<byte[]> processDataBeforeSend() {
                //通过工具类得到一个指令的byte[]数据,以文本为例
                List<byte[]> list = new ArrayList<>();
                for (int i = 0; i < lists.size(); i++) {
                    AttributeBean data = lists.get(i);
                    if (data.getContext_type() == 1) {//图片
                        Bitmap bitmap = data.getBitmap();
                        printBitmap(list, bitmap);
                    } else {
                        list.add(DataForSendToPrinterPos58.initializePrinter());
                        list.add(DataForSendToPrinterPos58.selectAlignment(data.getFont_gray()));
                        if (data.getFont_size() != 0) {
                            list.add(DataForSendToPrinterPos58.selectCharacterSize(17));//字体放大一倍
                        }
                        list.add(StringUtils.strTobytes(data.getContext()));
                    }
                    if(data.isFont_line()){
                        list.add(DataForSendToPrinterPos80.printAndFeedLine());
                    }
                }

                    byte[] cut = {0x1D, 0x56, 0x00};
                    list.add(cut);
                    return list;
            }
        });

    }

    private static void printBitmap(List<byte[]> list, Bitmap bitmap) {
        if (bitmap != null) {
            list.add(DataForSendToPrinterPos58.initializePrinter());
            List<Bitmap> blist;
            if(NewPrint.paperSize == 80){
                blist = BitmapProcess.cutBitmap(150, bitmap);
            }else {
                blist = BitmapProcess.cutBitmap(50,bitmap);
            }

            for (int j = 0; j < blist.size(); j++) {
                if(NewPrint.paperSize == 80){
                    list.add(DataForSendToPrinterPos80.printRasterBmp(0,blist.get(j), BitmapToByteData.BmpType.Dithering, BitmapToByteData.AlignType.Center,576));
                }else {
                    list.add(DataForSendToPrinterPos80.printRasterBmp(0,blist.get(j), BitmapToByteData.BmpType.Threshold, BitmapToByteData.AlignType.Center,384));
                }
            }
        }
    }

    @Override
    public void printStringAndBitmap(final List<String> lists, final LinkedHashMap<Integer,Bitmap> bitmapHashMap) {
        binder.WriteSendData(new TaskCallback() {
            @Override
            public void OnSucceed() {
                // TODO Auto-generated method stub
                // Toast.makeText(mContext, "打印成功", Toast.LENGTH_SHORT).show();
                mCallBack.onPrintResult(true);
            }
            @Override
            public void OnFailed() {
                // TODO Auto-generated method stub
                mCallBack.onPrintResult(false);
                //  Toast.makeText(mContext, "打印失败", Toast.LENGTH_SHORT).show();
            }
        }, new ProcessData() {//第二个参数是ProcessData接口的实现
            //这个接口的重写processDataBeforeSend这个处理你要发送的指令
            @Override
            public List<byte[]> processDataBeforeSend() {
                //通过工具类得到一个指令的byte[]数据,以文本为例
                List<byte[]> list = new ArrayList<>();
                for (int i = 0; i < lists.size(); i++) {
                    list.add(DataForSendToPrinterPos58.initializePrinter());
                    if(i == 0 || i == 1 ){
                        list.add(DataForSendToPrinterPos58.selectCharacterSize(17));//字体放大一倍
                        list.add(DataForSendToPrinterPos58.selectAlignment(1));//居中
                        list.add(StringUtils.strTobytes(lists.get(i)));
                        list.add(DataForSendToPrinterPos58.printAndFeedLine());
                    }else {
                        list.add(StringUtils.strTobytes(lists.get(i)));
                        list.add(DataForSendToPrinterPos58.printAndFeedLine());
                    }

                    Bitmap bitmap = bitmapHashMap.get(i);
                    printBitmap(list, bitmap);
                }
                if (bitmapHashMap.size() > 0) {
                    list.add(DataForSendToPrinterPos58.initializePrinter());
                    //传入的position位置大于list的话默认在最后面打印
                    for (Map.Entry<Integer, Bitmap> entry : bitmapHashMap.entrySet()) {
                        if (entry.getKey() > lists.size() - 1) {
                            Bitmap showBitmap = entry.getValue();
                            printBitmap(list, showBitmap);
                        }
                    }
                }
                byte[] cut = {0x1D, 0x56, 0x00};
                list.add(cut);
                return list;
            }
        });
    }

    @Override
    public void blueConnect(final String address) {
        Log.d("PrintBluetooth", "blueConnect: "+address);

        if(binder == null){
            Log.d("PrintBluetooth", "binder 为空: "+address);
            return;
        }

        binder.ConnectBtPort(address, new TaskCallback() {
            @Override
            public void OnSucceed() {
                Log.d("PrintBluetooth", "OnSucceed: "+address);
                //连接成功后在UI线程中的执行
                PrintSharedPreferencesUtils.setParam(mContext,"addressId",address);
                isConnect=true;
                mCallBack.onConnect("连接成功",true);
            }

            @Override
            public void OnFailed() {
                //连接失败后在UI线程中的执行
                mCallBack.onConnect("连接失败",false);
                isConnect=false;
                Toast.makeText(mContext, "蓝牙连接失败", Toast.LENGTH_LONG).show();
                //  ButConnect.setText("连接失败");
            }
        });
    }

    private void myDisBlueConnect() {
        if (isConnect) {
            //如果是连接状态才执行断开操作

            binder.DisconnectCurrentPort(new TaskCallback() {
                @Override
                public void OnSucceed() {
                    // TODO Auto-generated method stub
                    // textTitle.setText("请选择需要连接的打印机");
                    // Toast.makeText(mContext, "断开连接成功", Toast.LENGTH_LONG).show();
                    Log.d("tag", "disBlueConnect: 断开连接成功");
                    isConnect=false;
//                    isCT=false;
                    mCallBack.onDisConnect("断开成功",true);
                    //  ButConnect.setText("连接");
                }
                @Override
                public void OnFailed() {
                    //Toast.makeText(mContext, "断开连接成功", Toast.LENGTH_LONG).show();
                }
            });
        }else{
            Log.d("tag", "disBlueConnect: 当前并未连接");
            //  Toast.makeText(mContext, "当前并未连接", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void disBlueConnect() {
        if (isConnect) {
            //如果是连接状态才执行断开操作

            binder.DisconnectCurrentPort(new TaskCallback() {
                @Override
                public void OnSucceed() {
                    // TODO Auto-generated method stub
                    // textTitle.setText("请选择需要连接的打印机");
                    // Toast.makeText(mContext, "断开连接成功", Toast.LENGTH_LONG).show();
                    Log.d("tag", "disBlueConnect: 断开连接成功");
                    isConnect=false;
//                    isCT=false;
                    mCallBack.onDisConnect("断开成功",true);
                    //  ButConnect.setText("连接");
                }
                @Override
                public void OnFailed() {
                    // TODO Auto-generated method stub
                    //Toast.makeText(mContext, "断开连接成功", Toast.LENGTH_LONG).show();
                }
            });
        }else{
            Log.d("tag", "disBlueConnect: 当前并未连接");
            //  Toast.makeText(mContext, "当前并未连接", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void openMoneyBox() {

    }

    @Override
    public boolean isConnected() {
        if (isConnect) {
            return true;
        }else{
            return false;
        }
    }

    public ServiceConnection conn=new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
            Log.d("PrintBluetooth", "onServiceConnected: false");
        }
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            //绑定成功
            Log.d("PrintBluetooth", "onServiceConnected: true");
            binder=(IMyBinder) service;
            Log.i("PrintBluetooth:进来初始化", "" + isConnect);
            String Address = PrintSharedPreferencesUtils.getParam(mContext, "addressId", "");
            blueConnect(Address);
        }
    };

    @Override
    public void printString(List<AttributeBean> testList, int width) {
        printString(testList);
    }

}
